﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Data;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;
using QuanLyKho.PhongCat;

namespace QuanLyKho.QuanLyKho
{
    public partial class DanhSachLenh : UserControl
    {
        public DanhSachLenh()
        {
            InitializeComponent();
            Loaddata();
            SetPropertiesGrid();
            SetPropertiesColumns();
        }

        public void Loaddata()
        {
            var tuNgay = dtTuNgay.Checked ? dtTuNgay.Value.ToString("MM/dd/yyyy") : DateTime.Now.Month + "/01/" + DateTime.Now.Year;
            var denNgay = dtDenNgay.Checked ? dtDenNgay.Value.ToString("MM/dd/yyyy") : DateTime.Now.Month + "/"
                + DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) + "/" + DateTime.Now.Year;

            DataTable dtMau = DataAll.SelectAll("LenhSanXuat inner join PhongMau_SanPham On LenhSanXuat.IdSanPham = PhongMau_SanPham.IdSanPham",
                "LenhSanXuat.[ID],PhongMau_SanPham.[MaHang] as MaSanPham,LenhSanXuat.[IdSanPham],[NgayLapLenh],[NguoiLapLenh],LenhSanXuat.[SoLuong],[NgayGuiLenh],[NgaySuaLenh],[NgayDuyetLenh],LenhSanXuat.[TrangThai],[NgayChungTu],[NgayHoachToan],LenhSanXuat.[SoChungTu],LenhSanXuat.[GhiChu],[KhoDen],[KhoDi],[SXTuNgay],[SXDenNgay]",
                "WHERE LenhSanXuat.TrangThai = " + Convert.ToInt32(TrangThai.LenhSanXuat_ChotLenh));

            gridLenh.DataSource = dtMau;
            DataTable data = DataAll.SelectAll("LenhSanXuat inner join PhongMau_SanPham On LenhSanXuat.IdSanPham = PhongMau_SanPham.IdSanPham",
                "LenhSanXuat.NgayCapNhatKho,LenhSanXuat.[ID],PhongMau_SanPham.[MaHang] as MaSanPham,LenhSanXuat.[IdSanPham],[NgayLapLenh],[NguoiLapLenh],LenhSanXuat.[SoLuong],[NgayGuiLenh],[NgaySuaLenh],[NgayDuyetLenh],LenhSanXuat.[TrangThai],[NgayChungTu],[NgayHoachToan],LenhSanXuat.[SoChungTu],LenhSanXuat.[GhiChu],[KhoDen],[KhoDi],[SXTuNgay],[SXDenNgay]",
                "WHERE (LenhSanXuat.TrangThai = " + Convert.ToInt32(TrangThai.LenhSanXuat_CapNhatKho) + ") AND (CONVERT(DATE, LenhSanXuat.NgayCapNhatKho, 0) >= CONVERT(DATE,'" + tuNgay + "', 0) AND CONVERT(DATE, LenhSanXuat.NgayCapNhatKho, 0) <= CONVERT(DATE,'" + denNgay + "' , 0))");
            gridLenhUpdate.DataSource = data;
        }

        public void SetPropertiesGrid()
        {
            gvLenhUpdate.BestFitColumns();
            gvLenhUpdate.OptionsBehavior.Editable = false;
            gvLenhUpdate.FocusRectStyle = DrawFocusRectStyle.RowFullFocus;
            gvLenhUpdate.Appearance.SelectedRow.BackColor = Color.Empty;
            gvLenhUpdate.Appearance.SelectedRow.Options.UseBackColor = true;
            gvLenhUpdate.OptionsView.ShowGroupPanel = false;
            gvLenhUpdate.OptionsView.ShowFooter = true;
            gvLenhUpdate.OptionsFind.AlwaysVisible = true;
            gvLenhUpdate.Columns["ID"].Visible = false;

            gvLenh.BestFitColumns();
            gvLenh.FocusRectStyle = DrawFocusRectStyle.RowFullFocus;
            //gvLenh.OptionsBehavior.Editable = false;
            gvLenh.OptionsSelection.MultiSelect = true;
            gvLenh.OptionsView.ShowGroupPanel = false;
            //gvNhapKho.OptionsView.ColumnAutoWidth = false;
            gvLenh.OptionsView.ShowFooter = true;
            gvLenh.OptionsFind.AlwaysVisible = true;
            gvLenh.Columns["ID"].Visible = false;
            for (int i = 3; i < gvLenh.Columns.Count; i++)
            {
                gvLenh.Columns[i].OptionsColumn.AllowEdit = false;
            }
        }

        public void SetPropertiesColumns()
        {
            gcCapNhat.Width = 60;
            gcKhongCapNhat.Width = 60;
            gcCapNhat.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcKhongCapNhat.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            //gcS.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            //gcM.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            //gcL.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            //gcXL.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            //gcTongCan.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            //gcDMTT.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            //gcSLCan.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
        }

        private void gvLenh_DoubleClick(object sender, EventArgs e)
        {
            if (gvLenh.RowCount > 0)
            {
                CapNhatLenh.IdLenh = gvLenh.Columns["ID"].View.GetRowCellDisplayText(gvLenh.FocusedRowHandle, "ID");
                var lss = new CapNhatLenh();
                lss.ShowDialog();
                Loaddata();
                CapNhatLenh.IdLenh = "0";
            }

        }

        private void btnCapNhat_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var dataview = (DataView)gvLenh.DataSource;
            DialogResult dialogResult = MessageBox.Show("Bạn có chắc chắn muốn cập nhật kho.", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Yes)
            {
                string message = DataAll.Update("LenhSanXuat", "TrangThai =" + Convert.ToInt32(TrangThai.LenhSanXuat_CapNhatKho) +
                    ",NgayCapNhatKho = '" + DateTime.Now.ToString("MM/dd/yyyy") + "' WHERE ID =" + dataview[gvLenh.FocusedRowHandle]["ID"]);
                if (message.Equals("success"))
                {
                    try
                    {
                        var data = DataAll.SelectAll("LenhSanXuat_ChiTiet", "*", " WHERE IDLenhSanXuat = " + gvLenh.GetDataRow(gvLenh.FocusedRowHandle)["ID"]);
                        for (int i = 0; i < data.Rows.Count; i++)
                        {
                            var soluong = DataAll.SelectAll("Kho_VatTu", "SoLuong", " WHERE MaVatTu=N'" + data.Rows[i]["MaVatTu"] + "'");
                            DataAll.Update("Kho_VatTu", "SoLuong = " + Convert.ToString(Convert.ToInt32(soluong.Rows[0]["SoLuong"]) - Convert.ToInt32(data.Rows[i]["SoLuongCan"])) + " WHERE MaVatTu=N'" + data.Rows[i]["MaVatTu"] + "'");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Sửa số lượng vật tư dự kiến \n" + ex, "Message", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                    var dataht = DataAll.SelectAll("HanhTrinh", "*", " WHERE SoChungTu='" + dataview[gvLenh.FocusedRowHandle]["SoChungTu"]
                    + "' AND TrangThai=" + Convert.ToInt32(TrangThai.LenhSanXuat_CapNhatKho));
                    if (dataht.Rows.Count <= 0)
                    {
                        DataAll.InsertAll("HanhTrinh", dataview[gvLenh.FocusedRowHandle]["MaSanPham"]
                                                       + "," + Convert.ToInt32(PhongBan.KhoSX)
                                                       + "," + dataview[gvLenh.FocusedRowHandle]["SoChungTu"]
                                                       + "," + Convert.ToInt32(TrangThai.LenhSanXuat_CapNhatKho)
                                                       + "," + dataview[gvLenh.FocusedRowHandle]["NguoiLapLenh"]
                                                       + "," + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")
                                                       + "," + dataview[gvLenh.FocusedRowHandle]["SoLuong"]
                                                       + "," + Convert.ToDateTime(dataview[gvLenh.FocusedRowHandle]["SXDenNgay"].ToString()).ToString("MM/dd/yyyy")
                                                       + "," + Convert.ToDateTime(dataview[gvLenh.FocusedRowHandle]["SXDenNgay"].ToString()).ToString("MM/dd/yyyy"));
                    }
                    else
                    {
                        DataAll.Update("HanhTrinh", "NgayThang = '" + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff") + "' WHERE SoChungTu='" +
                                       dataview[gvLenh.FocusedRowHandle]["SoChungTu"]
                                       + "' AND TrangThai=" + Convert.ToInt32(TrangThai.LenhSanXuat_CapNhatKho));
                    }
                }
                MessageBox.Show(message.Equals("success") ? "Cập nhật kho thành công" : message, "Message",
                                    MessageBoxButtons.OK,
                                    message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                Loaddata();
            }
        }

        private void btnKhongCapNhat_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var dataview = (DataView)gvLenh.DataSource;
            DialogResult dialogResult = MessageBox.Show("Bạn có chắc chắn muốn từ chối cập nhật vào kho.", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Yes)
            {
                string message = DataAll.Update("LenhSanXuat", "TrangThai =" + Convert.ToInt32(TrangThai.LenhSanXuat_ChoDuyet) + " WHERE ID =" + dataview[gvLenh.FocusedRowHandle]["ID"]);
                MessageBox.Show(message.Equals("success") ? "Từ chối cập nhật thành công" : message, "Message",
                                    MessageBoxButtons.OK,
                                    message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                Loaddata();
            }
        }

        private void gvLenh_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "SXDenNgay")
            {
                TimeSpan songay = Convert.ToDateTime(e.CellValue) - DateTime.Now;
                if (0 < songay.Days && songay.Days < 5)
                {
                    e.Appearance.BackColor = Color.PaleGoldenrod;
                }
                if (songay.Days < 0)
                {
                    e.Appearance.BackColor = Color.DarkGray;
                }
            }
        }

        private void dtTuNgay_Leave(object sender, EventArgs e)
        {
            Loaddata();
        }

        private void dtDenNgay_Leave(object sender, EventArgs e)
        {
            Loaddata();
        }
    }
}
